import { toJS } from 'mobx';
import { inject, observer } from 'mobx-react';
import { WeaTools, WeaProgress, WeaDialog, WeaTab, WeaFormItem, WeaSearchGroup } from 'ecCom';
import { Button, Modal, message, Form, Rate } from 'antd';
import BaseList from './BaseList';
import ChanceForm from './Form';
import * as Bctt from '../constants/BaseListConstant';
import * as Fctt from '../constants/BaseFormConstant';
import SellChanceDiscuss from '../dialog/customerContactDialog';
import ChanceFormTab from './FormTab';
import { WeaLocaleProvider } from 'ecCom';

const getLabel = WeaLocaleProvider.getLabel;
import { WeaSwitch, WeaTableNew } from 'comsMobx';

const WeaTable = WeaTableNew.WeaTable;

@inject('chanceListStore')
@inject('chanceFormStore')
@observer
class List extends React.Component {
  // render before
  componentWillMount() {
    this.getStore().componentWillMount(this.props.params);
  }

  // render after
  componentDidMount() {
    this.getStore().componentDidMount();
  }

  // component remove before
  componentWillUnmount() {
    this.getStore().componentWillUnmount();
  }

  componentWillReceiveProps(nextProps) {
    const store = this.getStore();
    const oldType = store.routerParams.type;
    const newType = nextProps.params.type;
    // 切换路由或者点击菜单路由刷新组件
    if (oldType !== newType) {
      // component reload
      this.getStore().componentWillUnmount();
      this.getStore().componentWillMount(nextProps.params);
      this.getStore().componentDidMount();
      return;
    }
    const flag = this.props.hasOwnProperty('location');
    if (flag) {
      const keyOld = this.props.location.key;
      const keyNew = nextProps.location.key;
      if (keyOld !== keyNew) {
        // component reload
        this.getStore().componentWillUnmount();
        this.getStore().componentWillMount(nextProps.params);
        this.getStore().componentDidMount();
      }
    }
  }

  render() {
    const store = this.getStore();
    const { loading, titleName, titleIcon, showSearchAd, tableStore, searchKey } = store;

    const weaTableProps = {};// WeaTable中的属性集
    weaTableProps.comsWeaTableStore = tableStore;
    weaTableProps.hasOrder = true;
    weaTableProps.needScroll = true;
    if (this.reRenderColumns) { weaTableProps.getColumns = c => this.reRenderColumns(c); }
    if (this.onOperatesClick) { weaTableProps.onOperatesClick = (record, index, operate, flag) => this.onOperatesClick(record, index, operate, flag); }

    const tableCom = <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@02mcn3`} {...weaTableProps} tableWidth={this.getTableWidth.bind(this)} />;

    const searchTypes = this.getTabSearchTypes(store);
    let hasBase = false;
    let hasAdvanced = false;
    for (const t in searchTypes) {
      if (searchTypes[t] == Bctt.TAB_SEARCH_TYPE_BASE) {
        hasBase = true;
      }
      if (searchTypes[t] == Bctt.TAB_SEARCH_TYPE_ADVANCED) {
        hasAdvanced = true;
      }
    }
    let tabCom = null;
    const weaTabProps = {};// WeaTab中的属性集
    weaTabProps.buttons = this.getTabButtons(store);
    weaTabProps.searchType = searchTypes;
    let showWeaTab = false;
    if (hasBase) {
      showWeaTab = true;
      weaTabProps.searchsBaseValue = searchKey;
      weaTabProps.onSearch = store.doSearch;
      weaTabProps.onSearchChange = v => store.setSearchKey(v);
    }

    if (hasAdvanced) {
      showWeaTab = true;
      weaTabProps.showSearchAd = showSearchAd;
      weaTabProps.buttonsAd = this.getAdButtons(store);
      weaTabProps.setShowSearchAd = (bool) => { store.setShowSearchAd(bool); };
      weaTabProps.hideSearchAd = () => store.setShowSearchAd(false);
      weaTabProps.searchsAd = <Form ecId={`${this && this.props && this.props.ecId || ''}_Form@dl9n05`} horizontal>{this.getSearchConditionForm(store)}</Form>;
    }
    if (showWeaTab) { tabCom = <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@8y470u`} {...weaTabProps} />; }

    return (
      <div className="wea-crmReport-base">
        {tabCom}
        {tableCom}
        {this.renderAppend(store)}
      </div>
    );
  }

  excelExport(store) {
    store.excelExport(this.excelExportCallBack);
  }

  excelExportCallBack(data) {
    window.location = Bctt.ADDR_EXCEL_EXPORT;
  }

  getRightMenus(store) {
    const { rightMenu, tableStore } = store;
    const { doSearch } = store;
    const btnArr = [];
    const that = this;
    rightMenu && rightMenu.length > 0 && rightMenu.map((m) => {
      const disabled = m.isControl == '1' && toJS(tableStore.selectedRowKeys).length == 0;
      if (!disabled) {
        btnArr.push({
          key: m.type,
          icon: <i className={m.menuIcon} />,
          content: m.menuName,
          onClick: (key) => {
            if (key == Bctt.BTN_EXPORT) {
              that.excelExport(store);
            } else if (key == Bctt.BTN_SEARCH) {
              doSearch();
            } else if (key == Bctt.BTN_COLUMN) {
              tableStore.setColSetVisible(true);
              tableStore.tableColSet(true);
            } else {
              that.rightMenuClick(key);
            }
          },
        });
      }
    });
    return btnArr;
  }

  getTopButtons(store) {
    const { rightMenu, tableStore } = store;
    const btnArr = [];
    const that = this;
    rightMenu && rightMenu.length > 0 && rightMenu.map((m) => {
      m.isTop == '1' && btnArr.length < 4 && btnArr.push(
        <Button
          ecId={`${this && this.props && this.props.ecId || ''}_Button@910rx0@${m.type}`}
          type="primary"
          disabled={m.isControl == '1' && toJS(tableStore.selectedRowKeys).length == 0}
          onClick={() => {
            const fn = m.menuFun.indexOf('this') >= 0 ? `${m.menuFun.split('this')[0]})` : m.menuFun;
            if (m.type == Bctt.BTN_EXPORT) {
              that.excelExport(store);
            } else {
              that.rightMenuClick(m.type);
            }
          }}
        >
          {m.menuName}
        </Button>,
      );
    });
    const btnArrCustom = this.getTopButtonsCustom(store);
    return btnArrCustom.concat(btnArr);
  }

  getAdButtons(store) {
    const { doSearch, setShowSearchAd, resetAdFields } = store;
    return [
      (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@14uli5@search`} type="primary" onClick={() => { doSearch(); setShowSearchAd(false); }}>{getLabel(197, '搜索')}</Button>),
      (<Button
        ecId={`${this && this.props && this.props.ecId || ''}_Button@n6arl3@reset`}
        type="ghost"
        onClick={() => {
          resetAdFields();
        }}
      >{getLabel(2022, '重置')}</Button>),
      (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@w3jthw@cancel`} type="ghost" onClick={() => { setShowSearchAd(false); }}>{getLabel(201, '取消')}</Button>),
    ];
  }

  getStore() {
    return this.props.chanceListStore;
  }

  reRenderColumns(columns) {
    const store = this.getStore();
    const that = this;
    columns.forEach((c) => {
      if (c.dataIndex == 'id') {
        // 商机名称
        c.render = function (text, record) {
          const params = {};
          params.operation = 'edit';
          params.sellChanceId = record.id;
          params.customerid = store.customerId;
          params.selectedKey = 0;
          return <a onClick={() => { store.showChanceTabDialog(true, params, getLabel(367, '查看') + getLabel(32922, '商机')); }}>{record.idspan}</a>;
        };
      } else if (c.dataIndex == 'important') {
        c.render = function (text, record) {
          return <div><span><Rate ecId={`${this && this.props && this.props.ecId || ''}_Rate@z5j4ti`} count={1} value={text} onChange={(text) => { that.focusOnClick(record.important, record.randomFieldId); }} /></span></div>;
        };
      }
    });
    return columns;
  }

  onOperatesClick(record, index, operate, flag) {
    const store = this.getStore();
    if (operate.index == 0) {
      const params = {};
      params.operation = 'edit';
      params.sellChanceId = record.id;
      params.customerid = store.customerId;
      params.selectedKey = 0;
      store.showChanceTabDialog(true, params, getLabel(367, '查看') + getLabel(32922, '商机'));
    } else if (operate.index == 2) {
      Modal.confirm({
        title: getLabel(15172, '系统提示'),
        content: getLabel(83600, '您确认要删除吗？'),
        okText: getLabel(33703, '确定'),
        cancelText: getLabel(201, '取消'),
        onOk() {
          store.batchDelete(record.id);
        },
      });
    } else if (operate.index == 1) {
      const params = {};
      params.operation = 'edit';
      params.sellChanceId = record.id;
      params.customerid = store.customerId;
      params.selectedKey = 1;
      store.showChanceTabDialog(true, params, getLabel(367, '查看') + getLabel(32922, '商机'));
    }
  }

  getTabSearchTypes(store) {
    const arr = [];
    arr.push(Bctt.TAB_SEARCH_TYPE_BASE);
    arr.push(Bctt.TAB_SEARCH_TYPE_ADVANCED);
    return arr;
  }

  renderAppend(store) {
    const arr = [];
    const { chanceDialogTile, chanceDialogShow, showChanceDialog, chanceDialogParams, crmContactStore } = store;
    const { chanceTabDialogTile, chanceTabDialogShow, showChanceTabDialog, chanceTabDialogParams } = store;
    if (chanceDialogShow) {
      const buttons = this.props.chanceFormStore.getTopButtons();
      buttons.push(
        <Button
          ecId={`${this && this.props && this.props.ecId || ''}_Button@f57yi4@close`}
          onClick={() => {
            showChanceDialog(false);
            this.props.chanceFormStore.componentWillUnmount();
          }}
        >{getLabel(309, '关闭')}</Button>,
      );
      arr.push(<WeaDialog
        ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@i6b2fr@close`}
        icon="icon-coms-crm"
        iconBgcolor="#96358a"
        style={{ width: 1000, height: 600 }}
        visible={chanceDialogShow}
        title={chanceDialogTile}
        buttons={buttons}
        onCancel={() => {
          showChanceDialog(false);
          this.props.chanceFormStore.componentWillUnmount();
        }}
      >
        <ChanceForm ecId={`${this && this.props && this.props.ecId || ''}_ChanceForm@h0wsmv@cf`} params={chanceDialogParams} parentStore={store} />
      </WeaDialog>);
    }
    if (chanceTabDialogShow) {
      let buttons;
      if (chanceTabDialogParams.selectedKey == 0) {
        buttons = this.props.chanceFormStore.getTopButtons();
      } else {
        buttons = [];
      }
      buttons.push(
        <Button
          ecId={`${this && this.props && this.props.ecId || ''}_Button@b8spf6@close`}
          onClick={() => {
            showChanceTabDialog(false);
            this.props.chanceFormStore.componentWillUnmount();
          }}
        >{getLabel(309, '关闭')}</Button>,
      );
      arr.push(<WeaDialog
        ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@pvv7t9@dialog`}
        icon="icon-coms-crm"
        iconBgcolor="#96358a"
        style={{ width: 1000, height: 600 }}
        visible={chanceTabDialogShow}
        title={chanceTabDialogTile}
        buttons={buttons}
        onCancel={() => {
          showChanceTabDialog(false);
          this.props.chanceFormStore.componentWillUnmount();
        }}
      >
        <ChanceFormTab ecId={`${this && this.props && this.props.ecId || ''}_ChanceFormTab@7vm77h@cft`} params={chanceTabDialogParams} parentStore={store} />
      </WeaDialog>);
    }
    return arr;
  }

  rightMenuClick(key) {
    const store = this.getStore();
    if (key == Bctt.BTN_CREATE) {
      const params = {};
      params.operation = 'add';
      params.customerid = store.customerId;
      store.showChanceDialog(true, params, getLabel(82, '新建') + getLabel(32922, '商机'));
    } else if (key == Bctt.BTN_DELETEBATCH) {
      const selectedRowKeys = store.tableStore.selectedRowKeys;
      if (selectedRowKeys.length == 0) {
        message.warning(getLabel(22686, '请选择需要删除的数据！'));
        return;
      }
      Modal.confirm({
        title: getLabel(15172, '系统提示'),
        content: getLabel(83600, '您确认要删除吗？'),
        okText: getLabel(33703, '确定'),
        cancelText: getLabel(201, '取消'),
        onOk() {
          store.batchDelete(selectedRowKeys);
        },
      });
    }
  }

  getSearchConditionForm(store) {
    const { searchConditionComponents, searchConditionForm } = store;
    const groups = [];
    if (searchConditionComponents) {
      const { isFormInit } = searchConditionForm;
      const formParams = searchConditionForm.getFormParams();
      isFormInit && searchConditionComponents.map((c,indexGroup) => {
        const items = [];
        c.items.map((fields, index) => {
          items.push({
            com: (<WeaFormItem
              ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@fz5r4b@${index}`}
              label={`${fields.label}`}
              labelCol={{ span: `${fields.labelcol}` }}
              wrapperCol={{ span: `${fields.fieldcol}` }}
            >
              <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@bknjt0@${index}`} fieldConfig={fields} form={searchConditionForm} formParams={formParams} onChange={store.searchConditionFieldChange} onEnterSearch={this.onEnterSearch} />
            </WeaFormItem>),
            col: 2,
          });
        });
        groups.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@wbn9yv@${indexGroup}`} needTigger title={c.title} showGroup={c.defaultshow} items={items} />);
      });
    }
    return groups;
  }

  getTabButtons(store) {
    const arr = [];
    return arr;
  }

  onEnterSearch=() => {
    const store = this.getStore();
    store.doSearch();
    store.setShowSearchAd(false);
  }

    focusOnClick = (num, id) => { // 点击星星
      let flag = 1;
      if (num == '1') { flag = 0; }
      this.markTagsTo(flag, id);
    }
    markTagsTo(i, key) { // 重要  取消重要
      const { isMarkToImportant } = this.getStore();
      isMarkToImportant({ relatedIds: key, important: i, type: 'sellchance' });
    }

    getTableWidth = (columns) => {
      const showLength = columns.filter(col => col.display == 'true').length;
      return 120 * showLength;// 也支持返回固定值，如果小于100%,不会生效。
    }
}

export default WeaTools.tryCatch(React,
  props => <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@jzu2lr`} msg={props.error ? props.error : getLabel(129417, '服务器运行出错，请联系系统管理员！')} />,
  { error: '' })(List);
